/**
 * 进度管理器
 * 负责管理整个应用的加载进度，包括网站初始化、诗人切换等
 */

export class ProgressManager {
    constructor() {
        this.totalProgress = 0;
        this.currentTask = '';
        this.isVisible = false;
        this.callbacks = {
            onProgressUpdate: null,
            onTaskChange: null,
            onComplete: null
        };
        
        // 初始化进度条DOM元素
        this.initProgressBar();
    }

    /**
     * 初始化进度条DOM元素
     */
    initProgressBar() {
        // 检查是否已存在进度条
        if (document.getElementById('global-progress-bar')) {
            return;
        }

        // 创建进度条容器
        const progressContainer = document.createElement('div');
        progressContainer.id = 'global-progress-bar';
        progressContainer.className = 'progress-container';
        progressContainer.innerHTML = `
            <div class="progress-background">
                <div class="progress-fill" id="progress-fill"></div>
            </div>
            <div class="progress-text">
                <span id="progress-percentage">0%</span>
                <span id="progress-task">初始化中...</span>
            </div>
        `;

        // 添加到页面
        document.body.appendChild(progressContainer);

        // 添加样式
        this.addProgressStyles();
    }

    /**
     * 添加进度条样式
     */
    addProgressStyles() {
        if (document.getElementById('progress-styles')) {
            return;
        }

        const style = document.createElement('style');
        style.id = 'progress-styles';
        style.textContent = `
            .progress-container {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 60px;
                background: rgba(0, 0, 0, 0.8);
                backdrop-filter: blur(10px);
                z-index: 9999;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                transition: transform 0.3s ease, opacity 0.3s ease;
                transform: translateY(-100%);
                opacity: 0;
            }

            .progress-container.visible {
                transform: translateY(0);
                opacity: 1;
            }

            .progress-background {
                width: 80%;
                max-width: 400px;
                height: 8px;
                background: rgba(255, 255, 255, 0.2);
                border-radius: 4px;
                overflow: hidden;
                margin-bottom: 8px;
            }

            .progress-fill {
                height: 100%;
                background: linear-gradient(90deg, #007AFF, #5AC8FA);
                border-radius: 4px;
                width: 0%;
                transition: width 0.3s ease;
                position: relative;
                overflow: hidden;
            }

            .progress-fill::after {
                content: '';
                position: absolute;
                top: 0;
                left: -100%;
                width: 100%;
                height: 100%;
                background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
                animation: shimmer 2s infinite;
            }

            @keyframes shimmer {
                0% { left: -100%; }
                100% { left: 100%; }
            }

            .progress-text {
                display: flex;
                justify-content: space-between;
                width: 80%;
                max-width: 400px;
                color: white;
                font-size: 12px;
                font-weight: 500;
            }

            #progress-percentage {
                font-weight: 600;
            }

            #progress-task {
                opacity: 0.8;
            }

            /* 响应式设计 */
            @media (max-width: 768px) {
                .progress-container {
                    height: 50px;
                }
                
                .progress-background {
                    width: 90%;
                    height: 6px;
                }
                
                .progress-text {
                    width: 90%;
                    font-size: 11px;
                }
            }
        `;

        document.head.appendChild(style);
    }

    /**
     * 显示进度条
     */
    show() {
        this.isVisible = true;
        const container = document.getElementById('global-progress-bar');
        if (container) {
            container.classList.add('visible');
        }
    }

    /**
     * 隐藏进度条
     */
    hide() {
        this.isVisible = false;
        const container = document.getElementById('global-progress-bar');
        if (container) {
            container.classList.remove('visible');
            // 延迟移除DOM元素
            setTimeout(() => {
                if (!this.isVisible && container.parentNode) {
                    container.parentNode.removeChild(container);
                }
            }, 300);
        }
    }

    /**
     * 更新进度
     * @param {number} progress - 进度百分比 (0-100)
     * @param {string} task - 当前任务描述
     */
    updateProgress(progress, task = '') {
        this.totalProgress = Math.max(0, Math.min(100, progress));
        
        if (task) {
            this.currentTask = task;
        }

        // 更新DOM
        const fill = document.getElementById('progress-fill');
        const percentage = document.getElementById('progress-percentage');
        const taskElement = document.getElementById('progress-task');

        if (fill) {
            fill.style.width = `${this.totalProgress}%`;
        }
        
        if (percentage) {
            percentage.textContent = `${Math.round(this.totalProgress)}%`;
        }
        
        if (taskElement && this.currentTask) {
            taskElement.textContent = this.currentTask;
        }

        // 触发回调
        if (this.callbacks.onProgressUpdate) {
            this.callbacks.onProgressUpdate(this.totalProgress, this.currentTask);
        }

        // 如果进度完成，触发完成回调
        if (this.totalProgress >= 100) {
            setTimeout(() => {
                if (this.callbacks.onComplete) {
                    this.callbacks.onComplete();
                }
                this.hide();
            }, 500);
        }
    }

    /**
     * 设置任务
     * @param {string} task - 任务描述
     */
    setTask(task) {
        this.currentTask = task;
        
        const taskElement = document.getElementById('progress-task');
        if (taskElement) {
            taskElement.textContent = task;
        }

        if (this.callbacks.onTaskChange) {
            this.callbacks.onTaskChange(task);
        }
    }

    /**
     * 注册回调函数
     * @param {string} event - 事件类型
     * @param {Function} callback - 回调函数
     */
    on(event, callback) {
        if (this.callbacks[event] !== undefined) {
            this.callbacks[event] = callback;
        }
    }

    /**
     * 开始加载流程
     */
    startLoading() {
        this.show();
        this.updateProgress(0, '初始化应用...');
    }

    /**
     * 完成加载
     */
    completeLoading() {
        this.updateProgress(100, '加载完成');
        setTimeout(() => {
            this.hide();
        }, 1000);
    }

    /**
     * 模拟渐进式加载（用于测试）
     * @param {number} duration - 加载时长（毫秒）
     * @param {string} task - 任务描述
     */
    simulateLoading(duration = 3000, task = '加载中...') {
        this.show();
        this.setTask(task);
        
        let startTime = Date.now();
        const animate = () => {
            const elapsed = Date.now() - startTime;
            const progress = Math.min(100, (elapsed / duration) * 100);
            
            this.updateProgress(progress);
            
            if (progress < 100) {
                requestAnimationFrame(animate);
            }
        };
        
        animate();
    }

    /**
     * 获取当前进度
     */
    getProgress() {
        return this.totalProgress;
    }

    /**
     * 获取当前任务
     */
    getCurrentTask() {
        return this.currentTask;
    }

    /**
     * 销毁进度管理器
     */
    destroy() {
        this.hide();
        
        // 移除样式
        const styles = document.getElementById('progress-styles');
        if (styles && styles.parentNode) {
            styles.parentNode.removeChild(styles);
        }
        
        // 清空回调
        this.callbacks = {
            onProgressUpdate: null,
            onTaskChange: null,
            onComplete: null
        };
    }
}